import React, { useState, useEffect } from 'react';
import { Tabs, Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadFile, UploadFileStatus } from 'antd/es/upload/interface';
import { uploadReport, listReports, getReportContent } from '@/services/reportService';

const { Dragger } = Upload;
const { TabPane } = Tabs;

interface HTMLFile extends UploadFile {
  content?: string;
}

const WeeklyMonthlyReport: React.FC = () => {
  const [files, setFiles] = useState<HTMLFile[]>([]);

  // 拉取文件列表和内容
  const fetchFiles = async () => {
    try {
      const listRes = await listReports();
      const fileList = listRes.data || [];
      const fileObjs = await Promise.all(
        fileList.map(async (filename: string) => {
          const contentRes = await getReportContent(filename);
          return {
            uid: filename,
            name: filename,
            status: 'done' as UploadFileStatus,
            content: contentRes.data,
          };
        })
      );
      setFiles(fileObjs);
    } catch (error) {
      message.error('获取报告列表失败');
    }
  };

  useEffect(() => {
    fetchFiles();
  }, []);

  // 上传逻辑
  const handleUpload = async (file: File) => {
    if (!file.name.endsWith('.html')) {
      message.error('只支持上传HTML文件！');
      return false;
    }
    try {
      await uploadReport(file);
      message.success(`${file.name} 上传成功`);
      fetchFiles();
    } catch (error) {
      message.error(`${file.name} 上传失败`);
    }
    return false; // 阻止自动上传
  };

  return (
    <div className="p-6">
      <div className="mb-6">
        <Dragger
          accept=".html"
          multiple={true}
          beforeUpload={handleUpload}
          showUploadList={false}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽HTML文件到此区域上传</p>
          <p className="ant-upload-hint">支持单个或批量上传HTML文件</p>
        </Dragger>
      </div>

      {files.length > 0 && (
        <div className="bg-gray-50 rounded-lg p-4 shadow-sm">
          <Tabs
            type="card"
            tabBarStyle={{
              background: '#f5f7fa',
              borderRadius: '8px 8px 0 0',
              padding: '4px 12px 0 12px',
            }}
            moreIcon={null}
          >
            {files.map((file) => (
              <TabPane tab={file.name} key={file.uid}>
                <div
                  className="bg-white rounded-lg shadow p-6 min-h-[300px] transition"
                  style={{ border: '1px solid #f0f0f0' }}
                  dangerouslySetInnerHTML={{ __html: file.content || '' }}
                />
              </TabPane>
            ))}
          </Tabs>
        </div>
      )}
    </div>
  );
};

export default WeeklyMonthlyReport; 